<?php

namespace GroupBuying;

use C\L\WebUserController;
use C\M\GroupBuyingUserOrder;
use Phalcon\Paginator\Factory;

class UserOrderController extends WebUserController
{
  /**
   * 列表、搜索接口
   **/
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $orderSn     = $this->request->getQuery('order_sn', 'string', null);
        $orderState  = $this->request->getQuery('order_state', 'string', null);

        $builder = $this
        ->modelsManager
        ->createBuilder()
        ->columns([
        'group_buying_user_order.*',
        'group_buying_order.sn',
        'group_buying_order.state',
        'shipment.id as shipment_id',
        ])
        ->from(['group_buying_user_order' => 'C\M\GroupBuyingUserOrder'])
        ->join(
            'C\M\GroupBuyingOrder',
            'group_buying_order.id = group_buying_user_order.group_buying_order_id',
            'group_buying_order'
        )
        ->leftJoin(
            'C\M\Shipment',
            'shipment.shipable_id = group_buying_user_order.id AND ' .
            'shipment.shipable_type = \'group_buying_user_order\'',
            'shipment'
        )
        ->where('group_buying_user_order.user_id = :user_id:', ['user_id' => $this->uid])
        ->groupBy('group_buying_user_order.id')
        ->orderBy('group_buying_user_order.id DESC');

        if ($orderSn) {
            $builder = $builder->andWhere('group_buying_order.sn LIKE :sn:', ['sn' => '%' . $orderSn . '%']);
        }
        if ($orderState) {
            $builder = $builder->andWhere('group_buying_order.state = :state:', ['state' => $orderState]);
        }

        $options = [
        'builder' => $builder,
        'limit'   => $perPage,
        'page'    => $currentPage,
        'adapter' => 'queryBuilder',
        ];

        $pagination = Factory::load($options)->getPaginate();

        $items = array_map(function ($item) {
            $data = $item->group_buying_user_order->toArray();
            $data['other_info']  = json_decode($data['other_info'], true);
            $data['order_sn']    = $item->sn;
            $data['order_state'] = $item->state;
            $data['shipment_id'] = $item->shipment_id;
            return $data;
        }, $pagination->items->toArray());

        $result = [
        'items' => $items,
        'pagination' => [
        'total'        => $pagination->total_items,
        'per_page'     => $pagination->limit,
        'total_page'   => $pagination->total_pages,
        'current_page' => $pagination->current,
        ],
        ];

        $this->success($result);
    }

  /**
   * 详情接口
   **/
    public function showAction()
    {
        $id      = $this->request->getQuery('id', 'int', 0);
        $userId  = $this->uid;

        $params = [
        'conditions' => 'id = :id: AND user_id = :user_id:',
        'bind' => [
        'id'      => $id,
        'user_id' => $userId
        ],
        ];

        $userOrder = GroupBuyingUserOrder::findFirst($params);
        $userOrder->other_info = json_decode($userOrder->other_info, true);

        $order = $userOrder->getGroupBuyingOrder([
        'columns' => ["sn", 'state']
        ]);

        $result = $userOrder->toArray();
        $result['order'] = $order;

        $this->success($result);
    }

    public function deliverAction()
    {
        $id     = $this->request->getPost('id', 'int', 0);
        $userId = $this->uid;

        $userOrder = GroupBuyingUserOrder::findFirst([
        'conditions' => 'id = :id: AND user_id = :user_id: AND state = :state:',
        'bind' => [
        'id'      => $id,
        'user_id' => $userId,
        'state'   => 'shipped',
        ]
        ]);
        if (!$userOrder) {
            return $this->error('未找到符合要求的订单');
        }

        $userOrder->state = 'delivered';
        $userOrder->save()
        ? $this->success()
        : $this->error();
    }

  /**
   * 下单接口
   **/
    public function confirmAction()
    {
        $this->checkAuth();
        $this->checkPaymentPassword();

        $userId          = $this->uid;
        $orderId         = $this->request->getPost('order_id', 'int', 0);
        $addressId       = $this->request->getPost('address_id', 'int', null);
        $quantity        = $this->request->getPost('quantity', 'int', 0);
        $paymentPassword = $this->request->getPost('payment_password', 'string', null);

        if (!$this->s_user->checkPayPwd($userId, $paymentPassword)) {
            return $this->error('支付密码错误');
        }

        $lockKey = "uid:$userId:group_buying_user_order_confirm";

        try {
            if (!$this->di['s_user']->lock($lockKey, 5)) {
                throw new \Exception('服务器繁忙，请稍后再试。');
            }

            $this->di['db']->begin();

            $this->s_group_buying_user_order->confirm($userId, $orderId, $quantity, $addressId);

            $this->di['db']->commit();
            $this->di['s_user']->unlock($lockKey);
            $this->success();
        } catch (\Exception $e) {
            if ($this->di['db']->isUnderTransaction()) {
                $this->di['db']->rollback();
            }

            $this->di['s_user']->unlock($lockKey);
            $this->error($e->getMessage());
        }
    }
}
